package com.baize.imagehandledemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

public class PermissionUtils {
    public static final int REQUEST_PERMISSIONS = 1;

    public static boolean hasPermissions(Context context, String... permissions) {
        if (context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     *  //申请权限
     *         val permissions = arrayOf(
     *             Manifest.permission.CAMERA,
     *             Manifest.permission.WRITE_EXTERNAL_STORAGE
     *         )
     * @param context
     * @param permission
     */
    public static void needsPermissions(Context context, String[] permission) {
        if (!hasPermissions(context, permission)) {
            ActivityCompat.requestPermissions((Activity) context, permission, REQUEST_PERMISSIONS);
        }
    }

    /**
     * 获取 APP 详情页面intent
     */
    public static Intent getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        return localIntent;
    }

    //权限申请结果
    public static void onPermissionsResult(Context context, int requestCode, String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSIONS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                Toast.makeText(context, "请您同意相关权限，以便应用正常使用~", Toast.LENGTH_SHORT).show();
                Intent intent = getAppDetailSettingIntent(context);
                context.startActivity(intent);
            }
        }
    }

}
